/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package movie.ejb;

import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import movie.entity.UserAccess;
import movie.utility.Utility;

/**
 *
 * @author admin
 */
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EjbUser {

	@PersistenceContext(unitName = "MoviePU")
	private EntityManager em;

	public UserAccess login(String userName, String password) {
		System.out.println("Login atempt ejb: " + userName);
		List<UserAccess> listAccount = em.createNamedQuery("UserAccess.findByUsernameNotDeleted")
				.setParameter("userName", userName)
				.getResultList();
		if (listAccount.isEmpty()) {
			return null;
		} else {
			String hashPassword = Utility.getHash(password);
			System.out.println(listAccount.get(0).getPassword());
			if (hashPassword.equals(listAccount.get(0).getPassword())) {
				return listAccount.get(0);
			} else {
				return null;
			}
		}
	}

	public void editUser(UserAccess user) {
		em.merge(user);
	}

	public List<UserAccess> getUsers() {
		System.out.println("get users");
		return em.createNamedQuery("UserAccess.findAllNotDeleted").getResultList();
	}

	public void deleteUser(Integer idUserAccess) {
		UserAccess user = em.find(UserAccess.class, idUserAccess);
		user.setDateDeleted(new Date());
	}

	public void addUser(UserAccess user) {
		user.setDateCreated(new Date());
		user.setActive(false);
		em.persist(user);
	}

	public UserAccess getUser(Integer idUserAccess) {
		return em.find(UserAccess.class, idUserAccess);
	}

	public boolean checkUsernameAvailable(String username) {
		if (em.createNamedQuery("UserAccess.findByUsernameNotDeleted").setParameter("userName", username).getResultList().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	public void changeActiveStatus(Integer idUserAccess) {
		UserAccess user = em.find(UserAccess.class, idUserAccess);
		user.setActive(!user.getActive());
	}
}
